package com.example.wisdombookstore.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wisdombookstore.entity.TbBookInfo;
import com.example.wisdombookstore.entity.TbClerk;
import com.example.wisdombookstore.entity.TbReplenishmentTask;
import com.example.wisdombookstore.mapper.TbBookInfoMapper;
import com.example.wisdombookstore.mapper.TbClerkMapper;
import com.example.wisdombookstore.mapper.TbReplenishmentTaskMapper;
import com.example.wisdombookstore.entity.*;
import com.example.wisdombookstore.mapper.*;
import com.example.wisdombookstore.service.IReplenishmentTaskService;
import com.example.wisdombookstore.util.DateTime;
import com.example.wisdombookstore.util.IdWorker;
import com.example.wisdombookstore.util.ResponseResult;
import com.example.wisdombookstore.util.StateConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: MaHan
 * @Date: Created in 14:49 2020/10/25
 * @Description:
 * @program: IntelliJ IDEA
 * @ClassName: ReplenishmentTaskImpl
 */
@Service
public class ReplenishmentTaskServiceImpl implements IReplenishmentTaskService {
    @Autowired
    private TbReplenishmentTaskMapper TbReplenishmentTaskMapper;

    @Autowired
    private TbBookInfoMapper tbBookInfoMapper;

    @Autowired
    private TbClerkMapper tbClerkMapper;


    @Autowired
    private IdWorker idWorker;


    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(ClerkServiceImpl.class);

    @Autowired
    private TbClerkMapper clerkMapper;

    @Autowired
    private TbReplenishmentTaskMapper recplenishmentTaskMapper;

    @Autowired
    private TbReplenishmentResultMapper replenishmentResultMapper;

    @Autowired
    private TbBookTypeMapper bookTypeMapper;

    @Autowired
    private TbBookMapper bookMapper;


    @Autowired
    private TbReplenishmentParticularMapper replenishmentParticularMapper;

    /**
     * TODO &马晗& 根据负责人查询补货任务
     *
     * @param tbUserCode: 负责人标识
     * @return: com.example.wisdombookstore.util.ResponseResult
     * @Author &马晗&
     * @Description
     * @Date 15:49 2020/10/25
     **/
    @Override
    public ResponseResult replenishmentUserFindCode(Long tbUserCode) {
        //提示信息
        ResponseResult result = new ResponseResult();
        //根据负责人查询任务
        QueryWrapper<TbReplenishmentTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbReplenishmentTask::getTbUserCode, tbUserCode);
        TbReplenishmentTask tbReplenishmentTask = TbReplenishmentTaskMapper.selectOne(queryWrapper);
        //获取书籍标识
        long tbBookInfoCode = tbReplenishmentTask.getTbBookInfoCode();
        //查询要补货的书籍
        QueryWrapper<TbBookInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(TbBookInfo::getCode, tbBookInfoCode);
        TbBookInfo tbBookInfo = tbBookInfoMapper.selectOne(qw);
        //带走
        tbReplenishmentTask.setTbBookInfo(tbBookInfo);
        //判断有没有该数据
        if (tbReplenishmentTask == null) {
            result.setFailMessage("没有该数据");
            return result;
        }
        //放入返回信息
        result.setResult(tbReplenishmentTask);
        return result;

    }

    @Override
    public ResponseResult replenishmentUserFindCodeList(Long tbUserCode) {
        //提示信息
        ResponseResult result = new ResponseResult();
        //根据负责人查询任务
        QueryWrapper<TbReplenishmentTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbReplenishmentTask::getTbUserCode, tbUserCode);
        List<TbReplenishmentTask> tbReplenishmentTasks = TbReplenishmentTaskMapper.selectList(queryWrapper);
        for(TbReplenishmentTask a:tbReplenishmentTasks){
            //判断有没有该数据
            if (a == null) {
                result.setFailMessage("没有该数据");
                //跳出本次循环
                break;
            }
            //获取书籍标识
            long tbBookInfoCode = a.getTbBookInfoCode();
            //查询要补货的书籍
            QueryWrapper<TbBookInfo> qw = new QueryWrapper<>();
            qw.lambda().eq(TbBookInfo::getCode, tbBookInfoCode);
            TbBookInfo tbBookInfo = tbBookInfoMapper.selectOne(qw);
            //带走
            a.setTbBookInfo(tbBookInfo);
        }
        //放入返回信息
        result.setResult(tbReplenishmentTasks);
        return result;
    }

    /**
     * TODO &马晗& 查询所有补货任务
     *
     * @param currentPage: 当前页
     * @param pageSize:    每页条数
     * @return: com.example.wisdombookstore.util.ResponseResult
     * @Author &马晗&
     * @Description
     * @Date 19:57 2020/10/25
     **/
    @Override
    public ResponseResult replenishmentUserFind(Integer currentPage, Integer pageSize) {
        //提示信息
        ResponseResult result = new ResponseResult();
        //分页插件
        Page<TbReplenishmentTask> page = new Page<>(currentPage, pageSize);
        //mybatis puls 插件
        QueryWrapper<TbReplenishmentTask> queryWrapper = new QueryWrapper<>();
        //查询所有补货任务
        Page<TbReplenishmentTask> tbReplenishmentTaskPage = this.TbReplenishmentTaskMapper.selectPage(page, queryWrapper);
        //取出集合
        List<TbReplenishmentTask> tbReplenishmentTasks = tbReplenishmentTaskPage.getRecords();
        for(TbReplenishmentTask tbReplenishmentTask:tbReplenishmentTasks){
            long tbBookInfoCode = tbReplenishmentTask.getTbBookInfoCode();
            //查询要补货的书籍
            QueryWrapper<TbBookInfo> qw = new QueryWrapper<>();
            qw.lambda().eq(TbBookInfo::getCode, tbBookInfoCode);
            TbBookInfo tbBookInfo = tbBookInfoMapper.selectOne(qw);
            //获取负责人标识
            Long tbUserCode = tbReplenishmentTask.getTbUserCode();
            QueryWrapper<TbClerk> qwu = new QueryWrapper<>();
            qwu.lambda().eq(TbClerk::getCode, tbUserCode);
            TbClerk tbClerk = tbClerkMapper.selectOne(qwu);

            //带走
            tbReplenishmentTask.setTbBookInfo(tbBookInfo);
            tbReplenishmentTask.setTbClerk(tbClerk);
        }
        //判断集合是否为空
        if (tbReplenishmentTasks.size() == StateConstant.HAVEHOT) {
            //如果为空提示没有该任务
            result.setFailMessage("没有任务");
            return result;
        }
        //如果不为空 返回数据
        result.setResult(tbReplenishmentTaskPage);
        return result;
    }


    @Override
    public ResponseResult creteReplenishmentTaskCode() {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String,Object> resultsMap=new HashMap<>();

        TbReplenishmentTask task = new TbReplenishmentTask();
        task.setCode(idWorker.nextId());
        int insert = this.TbReplenishmentTaskMapper.insert(task);
        resultsMap.put("replenishmentTask",task);
        result.setResult(resultsMap);
        result.setSuccess(true);
        return result;
    }

    @Override
    public ResponseResult createReplenishment(TbReplenishmentTask replenishmentTask, Long tbUserId, Long tbReplenishmentCode) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap=new HashMap<>();
        System.err.println(replenishmentTask+"-----"+tbUserId+"----------"+tbReplenishmentCode);
        try {
            //任务结束时间不可以小于开始时间
            System.err.println(replenishmentTask.getEndCheckDate().getTime()<replenishmentTask.getStartCheckDate().getTime());
            if (replenishmentTask.getEndCheckDate().getTime()<replenishmentTask.getStartCheckDate().getTime()){
                result.setFailMessage("日期错误");
                return result;
            };
            //任务开始时间不可以小于当前时间
            System.err.println(DateTime.getDateTime().getTime() >replenishmentTask.getStartCheckDate().getTime());
            if (DateTime.getDateTime().getTime() >replenishmentTask.getStartCheckDate().getTime()){
                result.setFailMessage("日期错误");
                return result;
            }
            QueryWrapper<TbReplenishmentTask> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(TbReplenishmentTask::getCode,tbReplenishmentCode);
            TbReplenishmentTask tbReplenishmentTask = recplenishmentTaskMapper.selectOne(wrapper);
            if (tbReplenishmentTask==null){
                result.setFailMessage("任务不存在");
                return result;
            }
            //日期格式化
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sfd1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //任务开始时间
            String startTime = sfd.format(replenishmentTask.getStartCheckDate().getTime());
            //任务结束时间
            String endTime = sfd1.format(replenishmentTask.getEndCheckDate().getTime());
            tbReplenishmentTask.setStartCheckDate(DateTime.getDateTime(startTime));
            tbReplenishmentTask.setEndCheckDate(DateTime.getDate(endTime));
            tbReplenishmentTask.setTargetNumber(replenishmentTask.getTargetNumber());
            tbReplenishmentTask.setTbUserCode(tbUserId);
            tbReplenishmentTask.setCreateTime(DateTime.getDateTime());
            tbReplenishmentTask.setTbBookInfoCode(replenishmentTask.getTbBookInfoCode());
            recplenishmentTaskMapper.update(tbReplenishmentTask,wrapper);
            //创建结果数据
            TbReplenishmentResult replenishmentResult=new TbReplenishmentResult();
            replenishmentResult.setTbReplenishmentTaskCode(tbReplenishmentCode);
            replenishmentResult.setCode(idWorker.nextId());
            replenishmentResult.setTbBookInfoCode(tbReplenishmentTask.getTbBookInfoCode());
            replenishmentResult.setTargetNumber(tbReplenishmentTask.getTargetNumber());
            replenishmentResult.setLackNumber(tbReplenishmentTask.getTargetNumber());
            //实际数量等于目标数量-剩余数量
            Integer realNumber=tbReplenishmentTask.getTargetNumber()-tbReplenishmentTask.getTargetNumber();
            replenishmentResult.setRealNumber(realNumber);
            replenishmentResult.setCreateTime(DateTime.getDateTime(startTime));
            replenishmentResult.setUpdateTime(DateTime.getDateTime(startTime));
            replenishmentResultMapper.insert(replenishmentResult);
            if (tbReplenishmentTask!=null){
                resultMap.put("task",tbReplenishmentTask);
                resultMap.put("result",replenishmentResult);
                result.setSuccess(true);
                result.setResult(resultMap);
                result.setMessage("添加成功");
                return result;
            }
            result.setFailMessage("添加失败");
            return result;
        }catch (Exception e) {
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult executeReplenishmentTask(Long tbUserId,Long tbReplenishmentResultCode,String rfidCode) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap=new HashMap<>();
        try {
            //查询任务的结果存不存在
            QueryWrapper<TbReplenishmentResult> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(TbReplenishmentResult::getCode,tbReplenishmentResultCode);
            TbReplenishmentResult replenishmentResult = replenishmentResultMapper.selectOne(wrapper);
            if (replenishmentResult==null){
                result.setFailMessage("任务不存在");
                return result;
            }
            if (replenishmentResult.getRealNumber().equals(replenishmentResult.getTargetNumber())){
                result.setFailMessage("任务已完成请提交任务");
                return result;
            }
            else {
                //查询书籍单品信息
                QueryWrapper<TbBook> bookWrapper = new QueryWrapper<>();
                bookWrapper.lambda().eq(TbBook::getRfIdCode, rfidCode);
                TbBook book = bookMapper.selectOne(bookWrapper);
                if (book == null) {
                    result.setFailMessage("书籍不存在");
                    return result;
                }
                //根据书籍单品信息查询书籍信息
                QueryWrapper<TbBookInfo> infoWrapper = new QueryWrapper<>();
                infoWrapper.lambda().eq(TbBookInfo::getCode, book.getTbBookInfoCode());
                TbBookInfo tbBookInfo = tbBookInfoMapper.selectOne(infoWrapper);
                //根据书籍信息查询书籍类型
                QueryWrapper<TbBookType> typeWrapper = new QueryWrapper<>();
                typeWrapper.lambda().eq(TbBookType::getCode, tbBookInfo.getTbBookTypeCode());
                TbBookType tbBookType = bookTypeMapper.selectOne(typeWrapper);

                //添加详细的补货记录
                TbReplenishmentParticular particular = new TbReplenishmentParticular();
                particular.setCode(idWorker.nextId());
                particular.setRfIdCode(rfidCode);
                particular.setTbBookCode(book.getCode());
                particular.setTbBookTypeCode(tbBookType.getCode());
                particular.setTbReplenishmentResultCode(tbReplenishmentResultCode);
                if (particular == null) {
                    result.setFailMessage("操作失败");
                    return result;
                }
                replenishmentParticularMapper.insert(particular);
                //已经补货的数量
                Integer realNumber = replenishmentResult.getRealNumber() + 1;
                replenishmentResult.setRealNumber(realNumber);
                //剩余数量
                Integer lackNumber = replenishmentResult.getLackNumber() - 1;
                replenishmentResult.setLackNumber(lackNumber);
                replenishmentResultMapper.update(replenishmentResult, wrapper);
                resultMap.put("particular", particular);
                resultMap.put("result", replenishmentResult);
                result.setResult(resultMap);
                result.setSuccess(true);
                result.setMessage("操作成功");
                result.setCode(1);
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }

    @Override
    public ResponseResult delReplenishmentTask(Long tbReplenishmentResultCode) {
        ResponseResult result=ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            QueryWrapper<TbReplenishmentTask> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(TbReplenishmentTask::getCode,tbReplenishmentResultCode);
            TbReplenishmentTask task = TbReplenishmentTaskMapper.selectOne(wrapper);
            if (task==null){
                result.setFailMessage("查无此任务");
                return result;
            }
            task.setIsDel(1);
            TbReplenishmentTaskMapper.update(task,wrapper);
            if (task==null){
                result.setFailMessage("取消失败");
                return result;
            }
            resultMap.put("task",task);
            result.setMessage("操作成功");
            result.setSuccess(true);
            result.setCode(1);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage("程序异常" + e.toString());
            result.setSuccess(false);
            return result;
        }
    }


}
